import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import './graphicsTest.css';
import returnButtonIcon from '../../asserts/img/graphics-test/return-button.png';

// 导入图案图片
import pattern1 from '../../asserts/img/graphics-test/1.png';
import pattern2 from '../../asserts/img/graphics-test/2.png';
import pattern3 from '../../asserts/img/graphics-test/3.png';
import pattern4 from '../../asserts/img/graphics-test/4.png';
import pattern5 from '../../asserts/img/graphics-test/5.png';
import pattern6 from '../../asserts/img/graphics-test/6.png';
import pattern7 from '../../asserts/img/graphics-test/7.png';
import pattern8 from '../../asserts/img/graphics-test/8.png';
import pattern9 from '../../asserts/img/graphics-test/9.png';

// 图案图片映射
const patternImages = {
  1: pattern1,
  2: pattern2,
  3: pattern3,
  4: pattern4,
  5: pattern5,
  6: pattern6,
  7: pattern7,
  8: pattern8,
  9: pattern9,
};

function GraphicsTestInterface() {
  const navigate = useNavigate();
  const location = useLocation();
  const scrollContainerRef = useRef(null);
  
  // 获取从上级页面传递的选中图案ID
  const selectedPatternId = location.state?.selectedPattern || 1;
  
  // 从配置文件读取倒计时设置
  const config = window.GRAPHICS_TEST_CONFIG || {};
  const initialCountdownValue = config.initialCountdown || 3;
  const testCountdownValue = config.testCountdown || 120;
  
  // 状态管理
  const [phase, setPhase] = useState('initial'); // 'initial', 'testing', 'finished'
  const [countdown, setCountdown] = useState(initialCountdownValue); // 初始倒计时
  const [testCountdown, setTestCountdown] = useState(testCountdownValue); // 测试倒计时
  const [imageRows, setImageRows] = useState([]);
  const [selectedImages, setSelectedImages] = useState(new Set());
  const [correctCount, setCorrectCount] = useState(0);
  const [wrongCount, setWrongCount] = useState(0);

  // 生成随机图片行（7张图片，相邻不重复，每行至少有1张目标图片）
  const generateImageRow = useCallback(() => {
    const row = [];
    let lastImage = null;
    const availableImages = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    
    // 先生成整行，确保相邻不重复
    for (let i = 0; i < 7; i++) {
      // 随机选择图片，确保与前一张不同
      const available = availableImages.filter(id => id !== lastImage);
      const imageId = available[Math.floor(Math.random() * available.length)];
      
      row.push({
        id: `${Date.now()}-${i}-${Math.random()}`,
        imageId,
        isTarget: imageId === selectedPatternId,
        selected: false,
        correct: null
      });
      
      lastImage = imageId;
    }
    
    // 检查是否包含目标图片
    const hasTarget = row.some(img => img.isTarget);
    
    // 如果没有目标图片，随机替换一个位置为目标图片（确保不与相邻重复）
    if (!hasTarget) {
      let replaced = false;
      // 尝试多次找到合适的位置
      for (let attempt = 0; attempt < 10 && !replaced; attempt++) {
        const targetPosition = Math.floor(Math.random() * 7);
        const prevId = targetPosition > 0 ? row[targetPosition - 1].imageId : null;
        const nextId = targetPosition < 6 ? row[targetPosition + 1].imageId : null;
        
        // 只有当目标图片与相邻图片都不同时才替换
        if (prevId !== selectedPatternId && nextId !== selectedPatternId) {
          row[targetPosition] = {
            ...row[targetPosition],
            imageId: selectedPatternId,
            isTarget: true
          };
          replaced = true;
        }
      }
      
      // 如果仍然无法替换，强制替换第一个不会造成相邻重复的位置
      if (!replaced) {
        for (let i = 0; i < 7; i++) {
          const prevId = i > 0 ? row[i - 1].imageId : null;
          const nextId = i < 6 ? row[i + 1].imageId : null;
          
          if (prevId !== selectedPatternId && nextId !== selectedPatternId) {
            row[i] = {
              ...row[i],
              imageId: selectedPatternId,
              isTarget: true
            };
            break;
          }
        }
      }
    }
    
    // 验证相邻图片不重复（调试用）
    for (let i = 1; i < row.length; i++) {
      if (row[i].imageId === row[i-1].imageId) {
        console.warn('⚠️ 发现相邻重复图片:', row[i-1].imageId, row[i].imageId);
      }
    }
    
    // 验证是否包含至少一个目标图片
    const finalHasTarget = row.some(img => img.isTarget);
    if (!finalHasTarget) {
      console.warn('⚠️ 未找到目标图片！');
    }
    
    console.log('📸 生成图片行:', row.map(img => img.imageId).join(' -> '));
    
    return row;
  }, [selectedPatternId]);

  // 初始化图片行
  useEffect(() => {
    if (phase === 'testing' && imageRows.length === 0) {
      console.log('🎬 测试阶段开始，初始化图片行');
      
      // 从配置文件读取总行数，默认50行
      const totalRows = window.GRAPHICS_TEST_CONFIG?.totalRows || 50;
      
      const initialRows = [];
      for (let i = 0; i < totalRows; i++) {
        initialRows.push(generateImageRow());
      }
      setImageRows(initialRows);
      console.log('📸 初始化完成，图片行数:', initialRows.length);
    }
  }, [phase, generateImageRow, imageRows.length]);

  // 初始倒计时逻辑
  useEffect(() => {
    if (phase === 'initial' && countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (phase === 'initial' && countdown === 0) {
      setPhase('testing');
      setTestCountdown(testCountdownValue);
    }
  }, [phase, countdown, testCountdownValue]);

  // 测试倒计时逻辑
  useEffect(() => {
    if (phase === 'testing' && testCountdown > 0) {
      const timer = setTimeout(() => {
        setTestCountdown(testCountdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    } else if (phase === 'testing' && testCountdown === 0) {
      console.log('🏁 测试完成!');
      console.log(`📊 最终统计: 正确 ${correctCount} 次，错误 ${wrongCount} 次`);
      console.log(`🎯 准确率: ${correctCount + wrongCount > 0 ? 
        ((correctCount / (correctCount + wrongCount)) * 100).toFixed(1) : 0}%`);
      
      // 跳转到结果页面，传递测试数据
      navigate('/graphics-test/result', {
        state: {
          correctCount,
          wrongCount,
          totalImages: imageRows.length * 7,
          totalRows: imageRows.length,
          selectedPattern: selectedPatternId
        }
      });
    }
  }, [phase, testCountdown, correctCount, wrongCount, navigate, imageRows.length, selectedPatternId]);


  // 图片点击处理
  const handleImageClick = (rowIndex, imageIndex) => {
    if (phase !== 'testing') return;
    
    const imageKey = `${rowIndex}-${imageIndex}`;
    if (selectedImages.has(imageKey)) return; // 已选中的图片不能重复选择
    
    // 检查当前行是否已经有图片被选中
    const rowHasSelection = imageRows[rowIndex].some(img => img.selected);
    if (rowHasSelection) {
      console.log('⚠️ 当前行已有图片被选中，不能再选择其他图片');
      return;
    }
    
    const image = imageRows[rowIndex][imageIndex];
    const isCorrect = image.isTarget;
    
    // 更新选中状态
    setSelectedImages(prev => new Set([...prev, imageKey]));
    
    // 更新图片状态
    setImageRows(prev => {
      const newRows = [...prev];
      newRows[rowIndex] = [...newRows[rowIndex]];
      newRows[rowIndex][imageIndex] = {
        ...newRows[rowIndex][imageIndex],
        selected: true,
        correct: isCorrect
      };
      return newRows;
    });
    
    // 更新统计
    if (isCorrect) {
      setCorrectCount(prev => {
        const newCount = prev + 1;
        console.log(`✅ 正确选择! 当前正确数: ${newCount}`);
        return newCount;
      });
    } else {
      setWrongCount(prev => {
        const newCount = prev + 1;
        console.log(`❌ 错误选择! 当前错误数: ${newCount}`);
        return newCount;
      });
    }
  };

  // 获取倒计时颜色
  const getCountdownColor = () => {
    if (phase === 'initial') return 'white';
    return 'white';
  };

  // 返回上级页面
  const handleGoBack = () => {
    navigate('/graphics-test');
  };


  return (
    <div className="graphics-test-interface">
      {/* 顶部导航 */}
      <div className="test-interface-header">
        <button 
          onClick={handleGoBack}
          className="return-button"
          style={{ backgroundImage: `url(${returnButtonIcon})` }}
          title="返回"
        >
        </button>
        
        <div className="countdown-display" style={{ color: getCountdownColor() }}>
          {phase === 'initial' && countdown > 0 && (
            <span className="initial-countdown">{countdown}</span>
          )}
          {phase === 'testing' && (
            <span className="test-countdown">
              {Math.floor(testCountdown / 60)}:{(testCountdown % 60).toString().padStart(2, '0')}
            </span>
          )}
        </div>
        
      </div>

      {/* 测试内容区域 */}
      <div 
        className="test-content"
        ref={scrollContainerRef}
        style={{ 
          overflowY: 'scroll',
          pointerEvents: phase === 'initial' ? 'none' : 'auto'
        }}
      >
        {phase === 'initial' && (
          <div className="initial-message">
            <p>准备开始测试...</p>
            <p>请选择与之前选定相同的图案</p>
          </div>
        )}
        
        {phase === 'testing' && (
          <div className="images-container">
            {imageRows.map((row, rowIndex) => {
              // 检查当前行是否已有图片被选中
              const rowHasSelection = row.some(img => img.selected);
              
              return (
                <div key={rowIndex} className="image-row">
                  {row.map((image, imageIndex) => (
                    <div
                      key={image.id}
                      className={`image-item ${image.selected ? 'selected' : ''} ${
                        image.correct === true ? 'correct' : 
                        image.correct === false ? 'wrong' : ''
                      } ${rowHasSelection && !image.selected ? 'disabled' : ''}`}
                      onClick={() => handleImageClick(rowIndex, imageIndex)}
                    >
                      <img 
                        src={patternImages[image.imageId]} 
                        alt={`图案 ${image.imageId}`}
                        className="pattern-test-image"
                      />
                    </div>
                  ))}
                </div>
              );
            })}
          </div>
        )}
      </div>

    </div>
  );
}

export default GraphicsTestInterface;
